package com.seecen.cywbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.cywbackend.mapper.CommentMapper;
import com.seecen.cywbackend.mapper.DynamicMapper;
import com.seecen.cywbackend.pojo.Like;
import com.seecen.cywbackend.service.LikeService;
import com.seecen.cywbackend.mapper.LikeMapper;
import com.seecen.cywbackend.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
* @author lenovo
* @description 针对表【t_like(点赞记录表)】的数据库操作Service实现
* @createDate 2025-03-23 22:19:42
*/
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like>
    implements LikeService{
    @Resource
    private LikeMapper likeMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    @Transactional
    public Result dynamicLike(Long userId, Integer dynamicId) {
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .eq(Like::getTargetId, dynamicId)
                .eq(Like::getTargetType, 1); // 1代表动态类型
        Like like = likeMapper.selectOne(wrapper);
        if (like != null) {
            likeMapper.deleteById(like.getId());
            dynamicMapper.decrementLikeCount(dynamicId);
        } else {
            Like newLike = new Like();
            newLike.setUserId(userId);
            newLike.setTargetId(dynamicId);
            newLike.setTargetType(1);
            newLike.setCreateTime(new Date());
            likeMapper.insert(newLike);
            dynamicMapper.incrementLikeCount(dynamicId);
        }
        return Result.ok(null);
    }

    @Override
    public Result commentLike(Long userId, Integer commentId) {
        LambdaQueryWrapper<Like> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Like::getUserId, userId)
                .eq(Like::getTargetId, commentId)
                .eq(Like::getTargetType, 2);
        if (likeMapper.selectOne(wrapper) != null) {
            likeMapper.delete(wrapper);
            commentMapper.decrementLikeCount(commentId);
        } else {
            Like newLike = new Like();
            newLike.setUserId(userId);
            newLike.setTargetId(commentId);
            newLike.setTargetType(2);
            newLike.setCreateTime(new Date());
            likeMapper.insert(newLike);
            commentMapper.incrementLikeCount(commentId);
        }
        return Result.ok(null);
    }
}




